package com.ybkj.o2o.sales.common.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.o2o.sales.common.Result;
import com.ybkj.o2o.sales.entity.passenger.Enterprise;
import com.ybkj.o2o.sales.entity.passenger.Passenger;
import com.ybkj.o2o.sales.entity.passenger.PassengerAccount;
import com.ybkj.o2o.sales.entity.passenger.PassengerAccount.PayType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shine on 15/9/28.
 */
@Component
public class PassengerApi {

  // public static final String API_GATEWAY_MC = "http://api.xiaoka.me/mc/";
  @Value("${spring.mc_url}")
//  http://123.56.82.81/mc/
  public String API_GATEWAY_MC;

  public static final String API_SERVICE_ID = "mc";

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private LoadBalancerClient loadBalancer;
  /**
   * 根据id查询单个用户.
   */
  public static final String ONE_PASSENGER = "api/passengers/";
  /**
   * 根据id查询单个企业用户.
   */
  public static final String ONE_ENTERPRISE = "api/enterprises/";

  /**
   * 添加客户财务记录(不可提现金额).
   */
  public static final String CREATE_PASSENGER_ACCOUNT = "api/passengers/";
  /**
   * 添加企业财务记录(不可提现金额).
   */
  public static final String CREATE_ENTERPRISE_ACCOUNT = "api/enterprises/";

  /**
   * 拼接地址.
   * 
   * @param serviceId 。。。
   * @param fallbackUrl 。。。
   * @return String
   */
  public String getRestUri(String serviceId, String fallbackUrl) {

    URI uri;
    try {
      ServiceInstance serviceInstance = loadBalancer.choose(serviceId);
      uri = serviceInstance.getUri();
    } catch (RuntimeException exo) {
      exo.printStackTrace();
      uri = URI.create(fallbackUrl);
    }

    String http = uri.toString();
    if (!http.endsWith("/")) {
      return http + "/";
    }

    return http;
  }

  /**
   * 根据乘客Id查询单个乘客.
   * 
   * @param passengerId 客户id
   * @param appKey 系统key
   * @return Passenger
   */
  public Passenger findOnePassenger(Long passengerId, String appKey) {

    Map<String, String> kv = new HashMap<>();
    kv.put("appKey", appKey);

    StringBuilder builder = new StringBuilder();
    builder.append(getRestUri(API_SERVICE_ID, API_GATEWAY_MC)).append(ONE_PASSENGER).append(passengerId).append("?appKey={appKey}");

    String response = restTemplate.getForObject(builder.toString(), String.class, kv);

    JSONObject jsonObject = JSON.parseObject(response);

    Passenger passenger = jsonObject.getObject("data", Passenger.class);

    return passenger;

  }

  /**
   * 查询单个企业用户.
   * 
   * @param enterpriseId 企业用户id
   * @param appKey 系统key
   * @return Enterprise
   */
  public Enterprise findOneEnterprise(Long enterpriseId, String appKey) {

    Map<String, String> kv = new HashMap<>();
    kv.put("appKey", appKey);


    StringBuilder builder = new StringBuilder();
    builder.append(getRestUri(API_SERVICE_ID, API_GATEWAY_MC)).append(ONE_ENTERPRISE)
        .append(enterpriseId).append("?appKey={appKey}");

    String response = restTemplate.getForObject(builder.toString(), String.class, kv);

    JSONObject jsonObject = JSON.parseObject(response);

    Enterprise enterprise = jsonObject.getObject("data", Enterprise.class);

    return enterprise;
  }

  /**
   * 
   * @param passenger
   * @param money
   * @param payType
   * @param operating
   * @param details
   * @param orderId
   * @param orderNo
   * @param orderType
   * @param updateBlance
   * @param appKey
   * @return
   */
  public Result<PassengerAccount> createPassengerAccount(Passenger passenger, BigDecimal money,
      PayType payType, String operating, String details, Long orderId, String orderNo,
      Integer orderType, Boolean updateBlance, String appKey) {
    Result<PassengerAccount> result = new Result<>();
    result.setSuccess(false);

    // 增加财务记录
    StringBuilder sb = new StringBuilder();
    sb.append(getRestUri(API_SERVICE_ID, API_GATEWAY_MC)).append(CREATE_PASSENGER_ACCOUNT)
        .append(passenger.getId()).append("/passengerNoDrawMoney").append("?appKey={appKey}");
    sb.append("&money={money}");
    sb.append("&payType={payType}");
    sb.append("&operator={operator}");

    Map<String, String> kv = new HashMap<>();
    kv.put("money", String.valueOf(money));
    kv.put("payType", String.valueOf(payType));
    kv.put("operator", String.valueOf(operating));

    if (StringUtils.isNotBlank(details)) {
      sb.append("&details={details}");
      kv.put("details", String.valueOf(details));
    }

    if (null != orderId && null != orderNo && null != orderType) {
      sb.append("&orderId={orderId}");
      sb.append("&orderNo={orderNo}");
      sb.append("&orderType={orderType}");

      kv.put("orderId", String.valueOf(orderId));
      kv.put("orderNo", String.valueOf(orderNo));
      kv.put("orderType", String.valueOf(orderType));
    }

    sb.append("&updateBlance={updateBlance}");
    kv.put("updateBlance", String.valueOf(updateBlance));
    kv.put("appKey", appKey);

    String reponse = restTemplate.postForObject(sb.toString(), null, String.class, kv);

    JSONObject jsonObject = JSON.parseObject(reponse);

    if (jsonObject.getIntValue("code") == 0) {
      result.setResult(jsonObject.getObject("data", PassengerAccount.class));
      result.setSuccess(true);
    } else {
      result.setMessage(jsonObject.getString("message"));
    }

    return result;

  }


  public Result<PassengerAccount> createEnterpriseAccount(Enterprise enterprise, BigDecimal money,
      PayType payType, String operating, String details, Long orderId, String orderNo,
      Integer orderType, Boolean updateBlance, String appKey) {

    Result<PassengerAccount> result = new Result<>();
    result.setSuccess(false);

    // 增加财务记录
    StringBuilder sb = new StringBuilder();
    sb.append(getRestUri(API_SERVICE_ID, API_GATEWAY_MC)).append(CREATE_ENTERPRISE_ACCOUNT)
        .append(enterprise.getId()).append("/accountNoDrawMoney").append("?appKey={appKey}");

    sb.append("&money={money}");
    sb.append("&payType={payType}");
    sb.append("&operator={operator}");

    Map<String, String> kv = new HashMap<>();
    kv.put("money", String.valueOf(money));
    kv.put("payType", String.valueOf(payType));
    kv.put("operator", String.valueOf(operating));

    if (StringUtils.isNotBlank(details)) {
      sb.append("&details={details}");
      kv.put("details", String.valueOf(details));
    }

    if (null != orderId && null != orderNo && null != orderType) {
      sb.append("&orderId={orderId}");
      sb.append("&orderNo={orderNo}");
      sb.append("&orderType={orderType}");

      kv.put("orderId", String.valueOf(orderId));
      kv.put("orderNo", String.valueOf(orderNo));
      kv.put("orderType", String.valueOf(orderType));
    }

    sb.append("&updateBlance={updateBlance}");
    kv.put("updateBlance", String.valueOf(updateBlance));
    kv.put("appKey", appKey);

    String reponse = restTemplate.postForObject(sb.toString(), null, String.class, kv);

    JSONObject jsonObject = JSON.parseObject(reponse);

    if (jsonObject.getIntValue("code") == 0) {
      result.setResult(jsonObject.getObject("data", PassengerAccount.class));
      result.setSuccess(true);
    } else {
      result.setMessage(jsonObject.getString("message"));
    }

    return result;
  }

}
